import logging
import platform
import re
import requests
import socket

logger = logging.getLogger("wechat.util")


def _get_linux_lan_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('www.baidu.com', 0))
        s.settimeout(5)
        ip = s.getsockname()[0]
    except Exception as e:
        logger.error(e)
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip


def get_lan_ip():
    """
    获取本机局域网IP
    """
    ip_address = "0.0.0.0"
    try:
        sys_str = platform.system()
        if sys_str == "Windows":
            ip_address = socket.gethostbyname(socket.gethostname())
            logger.debug("Windows @ " + ip_address)
        elif sys_str == "Linux":
            ip_address = _get_linux_lan_ip()
            logger.debug("Linux @ " + ip_address)
        elif sys_str == "Darwin":
            ip_address = socket.gethostbyname(socket.gethostname())
            logger.debug("Mac @ " + ip_address)
        else:
            logger.debug("Other System @ some ip")
    except Exception as e:
        logger.error(e)
    return ip_address


def get_local_public_ip():
    """
    获取本机公网IP
    """
    ip = "" 
    try:
        res = requests.get("https://myip.ipip.net", timeout=15).text
        ip = re.findall(r"(\d+\.\d+\.\d+\.\d+)", res)
        ip = ip[0] if ip else ""
    except Exception as e:
        logger.exception(e)
    return ip